<template>
  <div>
    <!-- 搜索条件开始-->
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="default"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            class="el-tree"
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            :default-expand-all="false"
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="用户名称" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入用户名称"
              clearable
              size="default"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model="queryParams.phonenumber"
              placeholder="请输入手机号码"
              clearable
              size="default"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="用户状态" clearable size="default">
              <el-option label="正常" value="0">正常</el-option>
              <el-option label="停用" value="1">停用</el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" size="default" @click="handleQuery">
              <i class="iconfont icon-chaxun">查询</i>
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button size="default" @click="resetQuery">
              <i class="iconfont icon-chongzhi">重置</i>
            </el-button>
          </el-col>
        </el-row>
        <!-- 搜索条件结束 -->
        <!--列表数据开始-->
        <el-table
          :header-cell-style="{background:'#f3f3f3'}"
          :border="true"
          ref="userTable"
          :data="userList"
          @selection-change="handleSelectionChange"
          v-loading="loading"
          height="550"
        >
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="用户编号" align="center" prop="userId" width="100"/>
          <el-table-column
            label="用户名称"
            align="center"
            prop="userName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="用户昵称"
            align="center"
            prop="nickName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="部门"
            align="center"
            prop="dept.deptName"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="手机号码" align="center" prop="phonenumber" width="120"/>
          <el-table-column label="状态" align="center" prop="status" v-if="columns[5].visible">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            v-if="columns[6].visible"
            width="160"
            :show-overflow-tooltip="true"
          >
            <template #default="scope">
              <span>{{ scope.row.createTime }}</span>
            </template>
          </el-table-column>
        </el-table>

        <Pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="pagination"
        />
      </el-col>
      <!--列表数据结束-->
    </el-row>
  </div>
</template>

<script>
//引入消息弹出框
import { ElMessageBox, ElMessage } from "element-plus";
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
  userExport,
  userdownload
} from "@/api/system/user";
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import { hasPermi } from "@/utils/auth";
import { getConfigKey } from "@/api/system/config";
//引入公共组件
import Pagination from "@/components/Pagination/index.vue"; //分页
import TreeSelect from "@/components/TreeSelect/index.vue"; //下拉树
export default {
  name: "User",
  components: {
    Pagination,
    TreeSelect
  },
  props: {
    xzryMsg: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken()
        },
        // 上传的地址
        url: "/system/user/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: "",
        phonenumber: "",
        status: "",
        deptId: ""
      },
      // 列信息
      columns: [
        {
          key: 0,
          label: `用户编号`,
          visible: true
        },
        {
          key: 1,
          label: `用户名称`,
          visible: true
        },
        {
          key: 2,
          label: `用户昵称`,
          visible: true
        },
        {
          key: 3,
          label: `部门`,
          visible: true
        },
        {
          key: 4,
          label: `手机号码`,
          visible: true
        },
        {
          key: 5,
          label: `状态`,
          visible: true
        },
        {
          key: 6,
          label: `创建时间`,
          visible: true
        }
      ]
    };
  },
  mounted() {
    // console.log("refs", this.$refs.userTable);
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getTreeselect();
    getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    /**权限问题 */
    permissiones(value) {
      return hasPermi(value);
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser({
        ...this.queryParams,
        beginTime: this.dateRange ? this.dateRange[0] : null,
        endTime: this.dateRange ? this.dateRange[1] : null
      }).then(response => {
        this.userList = response.rows;
        if (this.xzryMsg.length) {
          this.xzryMsg.map(res => {
            let index = this.userList.findIndex(a => a.userId == res.userId);
            this.$nextTick(() => {
              this.$refs.userTable.toggleRowSelection(this.userList[index]);
            });
          });
        }
        this.total = response.total;
        this.loading = false;
      }).catch(err=>{
        this.$message.error(err.msg)
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      ElMessageBox.confirm(
        '确认要"' + text + '""' + row.userName + '"用户吗？',
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return changeUserStatus(row.userId, row.status);
        })
        .then(() => {
          ElMessage({
            type: "success",
            message: text + "成功"
          });
        })
        .catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /**
     * 获取分页参数
     */
    pagination({ page, limit }) {
      this.queryParams.pageNum = page;
      this.queryParams.pageSize = limit;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.$refs.queryForm.resetFields();
      // this.resetForm('queryForm')
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.$emit("userId", selection);
    }
  }
};
</script>
<style lang="less" scoped>
.el-tree {
  border: solid 1px #eeeeee;
  overflow-y: scroll;
  max-height: 780px;
}
</style>
